package com.rskj.cashbook.controller;

import com.rskj.cashbook.response.ResponseEntity;
import com.rskj.cashbook.service.AutoAccountingRuleService;
import com.rskj.cashbook.vo.AutoAccountingRule;
import com.rskj.cashbook.vo.AutoAccountingExecutionLog;
import com.rskj.cashbook.vo.AutoAccountingRuleTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 自动记账规则控制器
 * @author system
 */
@RestController
@RequestMapping("/auto-accounting")
@CrossOrigin(origins = "*")
public class AutoAccountingRuleController {
    
    @Autowired
    private AutoAccountingRuleService autoAccountingRuleService;
    
    /**
     * 获取所有规则（分页）
     */
    @GetMapping("/rules")
    public ResponseEntity<com.github.pagehelper.PageInfo<AutoAccountingRule>> getAllRules(
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String ruleName,
            @RequestParam(required = false) String ruleType,
            @RequestParam(required = false) Boolean isActive) {
        try {
            com.github.pagehelper.PageInfo<AutoAccountingRule> result = autoAccountingRuleService.getRulesWithPageHelper(pageNumber, pageSize, ruleName, ruleType, isActive);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 获取所有规则（分页+排序）
     */
    @GetMapping("/rules/sorted")
    public ResponseEntity<com.github.pagehelper.PageInfo<AutoAccountingRule>> getAllRulesWithSort(
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String ruleName,
            @RequestParam(required = false) String ruleType,
            @RequestParam(required = false) Boolean isActive,
            @RequestParam(defaultValue = "create_time") String sortBy,
            @RequestParam(defaultValue = "DESC") String sortOrder) {
        try {
            com.github.pagehelper.PageInfo<AutoAccountingRule> result = autoAccountingRuleService.getRulesWithPageHelperAndSort(pageNumber, pageSize, ruleName, ruleType, isActive, sortBy, sortOrder);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 查询用户的所有规则（分页）
     */
    @GetMapping("/rules/user/{userId}/paged")
    public ResponseEntity<com.github.pagehelper.PageInfo<AutoAccountingRule>> getUserRulesWithPagination(
            @PathVariable String userId,
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String ruleName,
            @RequestParam(required = false) String ruleType,
            @RequestParam(required = false) Boolean isActive) {
        try {
            com.github.pagehelper.PageInfo<AutoAccountingRule> result = autoAccountingRuleService.getUserRulesWithPageHelper(userId, pageNumber, pageSize, ruleName, ruleType, isActive);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 创建规则
     */
    @PostMapping("/rules")
    public ResponseEntity<AutoAccountingRule> createRule(@RequestBody AutoAccountingRule rule) {
        try {
            AutoAccountingRule createdRule = autoAccountingRuleService.createRule(rule);
            return ResponseEntity.ok(createdRule);
        } catch (Exception e) {
            throw e; // 重新抛出异常，让全局异常处理器处理
        }
    }
    
    /**
     * 更新规则
     */
    @PutMapping("/rules/{id}")
    public ResponseEntity<AutoAccountingRule> updateRule(@PathVariable String id, @RequestBody AutoAccountingRule rule) {
        try {
            rule.setId(id);
            AutoAccountingRule updatedRule = autoAccountingRuleService.updateRule(rule);
            return ResponseEntity.ok(updatedRule);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 删除规则
     */
    @DeleteMapping("/rules/{id}")
    public ResponseEntity<Boolean> deleteRule(@PathVariable String id) {
        try {
            boolean result = autoAccountingRuleService.deleteRule(id);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 根据ID查询规则
     */
    @GetMapping("/rules/{id}")
    public ResponseEntity<AutoAccountingRule> getRuleById(@PathVariable String id) {
        try {
            AutoAccountingRule rule = autoAccountingRuleService.getRuleById(id);
            if (rule != null) {
                return ResponseEntity.ok(rule);
            } else {
                return ResponseEntity.failGeneric("规则不存在");
            }
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 查询用户的所有规则
     */
    @GetMapping("/rules/user/{userId}")
    public ResponseEntity<List<AutoAccountingRule>> getUserRules(@PathVariable String userId) {
        try {
            List<AutoAccountingRule> rules = autoAccountingRuleService.getUserRules(userId);
            return ResponseEntity.ok(rules);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 查询启用的规则
     */
    @GetMapping("/rules/active")
    public ResponseEntity<List<AutoAccountingRule>> getActiveRules() {
        try {
            List<AutoAccountingRule> rules = autoAccountingRuleService.getActiveRules();
            return ResponseEntity.ok(rules);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 启用/禁用规则
     */
    @PutMapping("/rules/{id}/toggle")
    public ResponseEntity<Boolean> toggleRuleStatus(@PathVariable String id) {
        try {
            boolean result = autoAccountingRuleService.toggleRuleStatus(id);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 切换规则状态（兼容前端调用）
     */
    @PutMapping("/rules/{id}/toggle-status")
    public ResponseEntity<Boolean> toggleRuleStatusCompatible(@PathVariable String id, @RequestBody Map<String, Object> request) {
        try {
            boolean result = autoAccountingRuleService.toggleRuleStatus(id);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 执行规则
     */
    @PostMapping("/rules/{id}/execute")
    public ResponseEntity<AutoAccountingExecutionLog> executeRule(@PathVariable String id) {
        try {
            AutoAccountingExecutionLog log = autoAccountingRuleService.executeRule(id);
            return ResponseEntity.ok(log);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 手动执行规则
     */
    @PostMapping("/rules/{id}/manual-execute")
    public ResponseEntity<AutoAccountingExecutionLog> manualExecuteRule(@PathVariable String id) {
        try {
            AutoAccountingExecutionLog log = autoAccountingRuleService.manualExecuteRule(id);
            return ResponseEntity.ok(log);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 批量执行规则
     */
    @PostMapping("/rules/batch-execute")
    public ResponseEntity<List<AutoAccountingExecutionLog>> executeRules(@RequestBody List<String> ruleIds) {
        try {
            List<AutoAccountingExecutionLog> logs = autoAccountingRuleService.executeRules(ruleIds);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 根据条件查询规则
     */
    @GetMapping("/rules/search")
    public ResponseEntity<List<AutoAccountingRule>> searchRules(
            @RequestParam(required = false) String ruleName,
            @RequestParam(required = false) String ruleType,
            @RequestParam(required = false) Boolean isActive,
            @RequestParam(required = false) String userId) {
        try {
            List<AutoAccountingRule> rules = autoAccountingRuleService.searchRules(ruleName, ruleType, isActive, userId);
            return ResponseEntity.ok(rules);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 获取规则执行历史
     */
    @GetMapping("/rules/{id}/history")
    public ResponseEntity<List<AutoAccountingExecutionLog>> getExecutionHistory(@PathVariable String id) {
        try {
            List<AutoAccountingExecutionLog> history = autoAccountingRuleService.getExecutionHistory(id);
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取自动记账规则统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats() {
        try {
            Map<String, Object> stats = autoAccountingRuleService.getStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            throw e;
        }
    }
    

    
    /**
     * 批量启用规则
     */
    @PutMapping("/rules/batch-enable")
    public ResponseEntity<Map<String, Object>> batchEnableRules(@RequestBody List<String> ruleIds) {
        try {
            Map<String, Object> result = autoAccountingRuleService.batchEnableRules(ruleIds);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 批量禁用规则
     */
    @PutMapping("/rules/batch-disable")
    public ResponseEntity<Map<String, Object>> batchDisableRules(@RequestBody List<String> ruleIds) {
        try {
            Map<String, Object> result = autoAccountingRuleService.batchDisableRules(ruleIds);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 批量删除规则
     */
    @DeleteMapping("/rules/batch-delete")
    public ResponseEntity<Map<String, Object>> batchDeleteRules(@RequestBody List<String> ruleIds) {
        try {
            Map<String, Object> result = autoAccountingRuleService.batchDeleteRules(ruleIds);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 导出规则配置
     */
    @GetMapping("/rules/export")
    public ResponseEntity<String> exportRules(@RequestParam(required = false) String format) {
        try {
            String exportData = autoAccountingRuleService.exportRules(format);
            return ResponseEntity.ok(exportData);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 导入规则配置
     */
    @PostMapping("/rules/import")
    public ResponseEntity<Map<String, Object>> importRules(@RequestBody String importData) {
        try {
            Map<String, Object> result = autoAccountingRuleService.importRules(importData);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
}
